﻿using Microsoft.Extensions.Hosting;
using MyCommon.Helper;
using MyCommon.LogHelper;
using MySerilog.Configuration;
using MySerilog.Extensions;
using Serilog;
using Serilog.Debugging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyExtension.ServiceExtensions
{
    public static class SerilogSetup
    {
        /// <summary>
        /// 使用Serilog记录日志
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static IHostBuilder AddSerilogSetup(this IHostBuilder hostBuilder) { 
            if (hostBuilder == null) throw new ArgumentNullException(nameof(hostBuilder));

            var loggerConfiguration = new LoggerConfiguration()
                .ReadFrom.Configuration(Appsettings.Configuration)
                .Enrich.FromLogContext()
                .WriteTo.MySQL(connectionString: Appsettings.app("ConnectionString"),"Log")
                .WriteToConsole()
                .WriteToFile()
                .WriteToLogBatching();

            Log.Logger = loggerConfiguration.CreateLogger();

            var file = File.CreateText(LogContextStatic.Combine($"SerilogDebug{DateTime.Now:yyyyMMdd}.txt"));
            SelfLog.Enable(TextWriter.Synchronized(file));

            hostBuilder.UseSerilog();

            return hostBuilder;
        }
    }
}
